#! python3
#Author: Heanny Liu
#time:18-6-27
#get sql data to bgp router

import telnetlib,time
from sqlLink import getSqlData
class telClass():
    ip='127.0.0.1'
    port = 2605
    pwd = 'zebra'
    timeout = 50


def telnet_network():
    tn = telnetlib.Telnet(telClass.ip, port=telClass.port, timeout=telClass.timeout) #23
    tn.read_until('Password:'.encode())
    tn.write( 'zebra\n'.encode())
    print ('input pwd')
    tn.read_until('bgpd>'.encode())
    print ('login success')
    tn.write('ena\n'.encode())
    tn.write('config t\n'.encode())
    time.sleep(1)
    tn.write('router bgp 131481\n'.encode())
    time.sleep(1)
    tn.write('network 1.2.3.4/32\n'.encode())
    print ('write end')
    result = tn.read_very_eager()
    print (result)
    tn.close()
    return True


def telnet_no_network():
    tn = telnetlib.Telnet(telClass.ip, port=telClass.port, timeout=telClass.timeout) #23
    tn.read_until('Password:'.encode())
    tn.write( 'zebra\n'.encode())
    print ('pwd end')
    time.sleep(1)
    tn.read_until('bgpd>'.encode())
    print ('login success')
    tn.write('ena\n'.encode())
    time.sleep(1)
    tn.write('config t\n'.encode())
    time.sleep(1)
    tn.write('router bgp 131481\n'.encode())
    time.sleep(1)
    tn.write('no network 1.2.3.4/32\n'.encode())
    print ('write end')
    result = tn.read_very_eager()
    print (result)
    tn.close()
    return True


def main():
    tn = telnetlib.Telnet(telClass.ip, port=2605, timeout=50) #23
    tn.read_until('Password:'.encode())
    tn.write( 'zebra\n'.encode())
    print ('pwd end')
    time.sleep(1)
    tn.read_until('bgpd>'.encode())
    print ('login success')
    tn.write('ena\n'.encode())
    time.sleep(1)
    tn.write('config t\n'.encode())
    time.sleep(1)
    reDatas = (getSqlData())
    tn.write('router bgp 131481\n'.encode())
    for reData in reDatas:
        time.sleep(1)
        tn.write('no network {}/32\n'.format(reData).encode())
    print ('write end')
    result = tn.read_very_eager()
    print (result)
    tn.close()
    return True
if __name__=='__main__':
    #telnetip()
    #reData = (getSqlData())
    main()
